package com.jh.user.service;

import cn.jh.common.exception.ServiceException;
import cn.jh.common.utils.CommonsUtil;
import cn.jh.common.utils.TokenUtil;
import com.jh.user.business.CongMingChannelBusiness;
import com.jh.user.pojo.CongMingChannel;
import com.jh.user.pojo.CongMingChannelRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

@RestController
public class CongMingChannelService {
    private static final Logger log = LoggerFactory.getLogger(CongMingChannelService.class);

    @Autowired
    private CongMingChannelBusiness congMingChannelBusiness;

    /**
     * 新增/修改快银通道
     * @param token
     * @param channelRequest
     * @param result
     * @param operating 0新增，1修改
     * @return
     */
    @PostMapping(value = "/v1.0/user/congmingchannel/addcongmingchannel/{token}")
    public Object addCongMingChannel(@PathVariable String token,
                                     CongMingChannel congMingChannel,
                                     @Valid CongMingChannelRequest channelRequest,
                                     BindingResult result,
                                     @RequestParam(value = "operating") String operating) {
        try {
            long userId = TokenUtil.getUserId(token);
        } catch (Exception e) {
            return CommonsUtil.returnError("token无效！");
        }
        try {
            if (result.hasErrors()) {
                StringBuffer sb = new StringBuffer();
                List<ObjectError> allErrors = result.getAllErrors();
                for (ObjectError error : allErrors) {
                    sb.append(error.getDefaultMessage());
                }
                return CommonsUtil.returnError(sb.toString());
            }
            Map<String, Object> resMap = congMingChannelBusiness.saveOfUpdateChannelInfo(congMingChannel, channelRequest, operating);
            if ("0".equals(operating)) {
                return CommonsUtil.returnSuccess("新增通道成功！", resMap);
            }
            return CommonsUtil.returnSuccess("通道修改成功！", resMap);
        } catch (ServiceException e) {
            e.printStackTrace();
            return CommonsUtil.returnError(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return CommonsUtil.returnError("服务器异常，请稍后再试！");
        }
    }
}
